import subprocess
import os
import time
import xml.dom
from xml.dom import minidom

port = 8888

t = raw_input("Amount of servers you wish to simulate?\n")

if t == '': server_count = 1
else: server_count = t
  
t = raw_input("and how many clients?\n")

if t == '': client_count = 1
else: client_count = t
  
current_path = os.getcwd()

os.chdir(current_path + '/controlserver/')

subprocess.Popen("./controlserver-32bit")

for i in range(int(server_count)):
  os.chdir(current_path + '/server/')
  
  doc = minidom.parse("settings.xml")
  port_node = doc.getElementsByTagName("port")[0]
  port_node.childNodes = [doc.createTextNode(str(port))]
  a = doc.toxml()
  test = open('settings.xml', 'w')
  test.write(a)
  test.close()
  
  subprocess.Popen("gnome-terminal -e 'python main.py'", shell=True)
  port = port + 1
  
  # wait since file writing takes so long
  time.sleep(2)
  
os.chdir(current_path + '/client/')
 
for i in range(int(client_count)):
  subprocess.Popen("gnome-terminal -e 'python dsgui.py'", shell=True)

q = raw_input("Press any key to exit.")

temp = ((subprocess.Popen(["ps u"], shell=True, stdout=subprocess.PIPE).stdout).read()).split("\n")[2:]
temp.remove('')

for t in reversed(temp):
  t = t.strip().split(" ")
  os.system("kill " + t[2])

print "Thanks for using happyChatSystems!"
